package com.j.lemon.learn.thread.blockingqueue;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * @Author lijunjun
 * @Date 2019-04-22 14:32
 * @Description  阻塞队列，队列先进先出
 *               ArrayListBlockingQueue 有界阻塞队列
 *               LinkedListBlockingQueue 有界阻塞队列，最大为Integer.MAX
 *
 *
 *
 * BlockingQueue接口的核心方法：
 *          方法类型        抛出异常        返回boolean值         阻塞          超时
 *          插入            add(e)        offer(e)             put(e)       offer(e,time,unit)
 *          删除            remove()      poll()               take()       poll(e,time,unit)
 *          检查            element()     peek()                无            无
 *
 */
public class BlockingQueueDemo {
    private LinkedBlockingDeque<String> queue = new LinkedBlockingDeque<>();

    private void product() throws InterruptedException {
        Thread.sleep(1000);
        queue.put("包子");
        System.out.println(Thread.currentThread().getName() + "生产了一个包子");
    }

    private void consume() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "来到商店");
        queue.take();
        System.out.println(Thread.currentThread().getName() + "吃了一个包子");
    }

    public static void main(String[] args) throws InterruptedException {
        BlockingQueueDemo blockingQueueDemo = new BlockingQueueDemo();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    blockingQueueDemo.product();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "商店").start();

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    blockingQueueDemo.consume();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
    }
}
